layui.use(['layer', 'form', 'table', 'template', 'configs', 'formSelects'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        template = layui.template,
        config = layui.configs,
        formSelects = layui.formSelects;

    //获取表格数据
    getTableData();

    function getTableData() {
        $.ajax({
            url: config.motorBaseUrl + "/controller_motors/sel/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    renderTable(result.data);
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //渲染表格
    function renderTable(data) {
        table.render({
            elem: '.settingTable'
            , id: 'trough-table'
            , data: data
            , autoSort: false
            , toolbar: '#toolbarTrough'
            , defaultToolbar: ['filter']
            , cols: [[
                {field: 'controllerId', title: '控制器id'}
                , {field: 'bitSn', title: '位序号'}
                , {field: 'motorIds', title: '马达ID'}
                , {field: 'motorNames', title: '马达位置'}
              /*  , {field: 'slotPosition', title: '槽位'}*/
                , {fixed: 'right', title: '操作', align: 'center', toolbar: '#rowOperate'}
            ]]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: 10
            , loading: true
        });
    }

    //头工具栏事件--新增
    table.on('toolbar(dataTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var event = obj.event;
        if (event === 'add') { //新增
            var layerIdx = layer.open({
                type: 1,
                title: "新增",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#rowAdd').html(),
                success: function (layero, index) {
                    form.render("select");
                    getControllerId(layero);
                    getMultiMotors1(layero, event);
                }
            });

            form.on('submit(rowAddForm)', function (res) {
                //console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                addDevice(res.field);
                layer.close(layerIdx);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            $(".add button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //监听工具条
    table.on('tool(dataTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'del') { //删除
            layer.confirm('真的删除吗？', function (index) {
                layer.close(index);
                deleteTrough(obj,data.id);
            });
        } else if (layEvent === 'edit') { //编辑
            var layerIdx = layer.open({
                type: 1,
                title: "编辑",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#rowEdit').html(),
                success: function (layero, index) {
                    form.val("rowEditForm", data);
                    getControllerId(layero,function(){
                        form.val("rowEditForm",{
                            "controllerId": data.controllerId
                        });
                    });
                    getMultiMotors(layero, layEvent, data);
                }
            });
            //form.val("rowEditForm", data);
            form.on('submit(rowEditForm)', function (res) {
                //console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                updateDevice(obj,res.field);
                layer.close(layerIdx);
                return false;
            });
            $(".edit button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //监听新增-启用开关
    form.on('switch(inUseNew)', function (data) {
        if (data.elem.checked) {
            data.value = 1;
        } else {
            data.value = 0;
        }
    });
    //监听编辑-启用开关
    form.on('switch(inUseEdit)', function (data) {
        if (data.elem.checked) {
            data.value = 1;
        } else {
            data.value = 0;
        }
    });

    //新增
    function addDevice(dataObj) {
        if (dataObj.inUse == undefined) {
            dataObj.inUse = 0;
        }
        $.ajax({
            url: config.motorBaseUrl + "/controller_motors/insert/v1.0",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //删除
    function deleteTrough(obj,data) {
        $.ajax({
            url: config.motorBaseUrl + "/controller_motors/del/v1.0",
            type: "post",
            datatype: "json",
            data: {"id": data},
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable('delete',obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    //更新
    function updateDevice(obj,dataObj) {
        $.ajax({
            url: config.motorBaseUrl + "/controller_motors/upd/v1.0",
            type: "post",
            datatype: "json",
            data:
            dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable("update",obj,dataObj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    function getMultiMotors(layero, layEvent, data) {
        $.ajax({
            url: config.motorBaseUrl + "/controller_motors/sel_motors_nu/v1.0",
            type: "post",
            datatype: "json",
            data: {
                motorIds: data.motorIds
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    layero.find(".multi-motors").html(template("motors-tpl", result));
                    formSelects.render('select-motor');
                    formSelects.btns('select-motor', ['select', 'remove', 'reverse'], {show: '', space: '10px'});
                    if (layEvent === 'edit') {
                        var motorIdsArr = data.motorIds.split(",");
                        formSelects.value('select-motor', motorIdsArr, true);
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    function getControllerId(layero,callback){
        $.ajax({
            url: config.motorBaseUrl + "/controller_motors/sel_controller/v1.0",
            type: "post",
            datatype: "json",
            data: "",
            success: function (result) {
                if (result.stateCode == 0) {
                    layero.find(".controllerId").html(template("controllerId-tpl", result));
                    form.render('select');
                    callback && callback();
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    };

    function getMultiMotors1(layero, layEvent, data) {
        $.ajax({
            url: config.motorBaseUrl + "/controller_motors/sel_motors/v1.0",
            type: "post",
            datatype: "json",
            data: "",
            success: function (result) {
                if (result.stateCode == 0) {
                    layero.find(".multi-motors").html(template("motors-tpl", result));
                    formSelects.render('select-motor');
                    formSelects.btns('select-motor', ['select', 'remove', 'reverse'], {show: '', space: '10px'});
                    if (layEvent === 'edit') {
                        var motorIdsArr = data.motorIds.split(",");
                        formSelects.value('select-motor', motorIdsArr, true);
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }


    function tableReload() {
        table.reload("trough-table", {
            url: config.motorBaseUrl + "/controller_motors/sel/v1.0"
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        })
    }

    function refreshTable(type,obj,data){
        if(type == "update"){
            obj.update(data); //同步更新缓存对应的值
        }else if(type == "delete"){
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        }
    }
});
